/**
 * 84. 柱状图中最大的矩形
 * https://leetcode-cn.com/problems/largest-rectangle-in-histogram/
 */

/**
 * @param {number[]} heights
 * @return {number}
 */
function largestRectangleArea(heights) {
  const { length } = heights;
  const lefts = new Array(length).fill(0);
  const rights = new Array(length).fill(0);
  const stack = new Array(length).fill(0);
  let top = -1;
  for (let i = 0; i < length; i += 1) {
    while (top >= 0 && heights[i] <= heights[stack[top]]) {
      top -= 1;
    }
    lefts[i] = top >= 0 ? stack[top] : -1;
    top += 1;
    stack[top] = i;
  }
  top = length;
  for (let i = length - 1; i >= 0; i -= 1) {
    while (top < length && heights[i] <= heights[stack[top]]) {
      top += 1;
    }
    rights[i] = top < length ? stack[top] : length;
    top -= 1;
    stack[top] = i;
  }
  let max = 0;
  for (let i = 0; i < length; i += 1) {
    const area = heights[i] * ((i - lefts[i] - 1) + (rights[i] - i - 1) + 1);
    if (area > max) {
      max = area;
    }
  }
  return max;
}

console.log(largestRectangleArea([2, 1, 5, 6, 2, 3]) === 10);
console.log(largestRectangleArea([2, 4]) === 4);
